/*
* @Author: Rex_li
* @Date:   2017-11-08 20:00:50
* @Last Modified by:   Rex_li
* @Last Modified time: 2018-12-04 22:23:08
*/
var express = require('express')
var request = require('request')
var http = require('https')
var cheerio = require('cheerio')
var OSS = require('ali-oss')
var STS = OSS.STS
var co = require('co')
var fs = require('fs')
var bodyParser = require('body-parser')
var app = express()

/*
* url 网络文件地址
* filename 文件名
* callback 回调函数
*/


app.use(bodyParser.json()) // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // support encoded bodies

app.all('*',function (req, res, next) {
	res.header('Access-Control-Allow-Origin', '*')
	// res.header('Access-Control-Allow-Origin', 'http://www.rextest.top')
	// res.header('Access-Control-Allow-Origin', 'http://www.chujiamen.com')
	res.header('Access-Control-Allow-Headers', 'Content-Type')
	res.header('Access-Control-Allow-Methods', 'POST, OPTIONS')
　next()　
})

app.post('/getimg', function (req, res) {
	var data = req.body.map(item => {
		var folder = item.id
		var img_src = item.url

		var img_filename = img_src.replace(/\/0\?wx\_fmt\=/g, '.').replace(/\/640\?wx\_fmt\=/g, '.').replace(/\&tp\=webp\&wxfrom\=5\&wx\_lazy\=1\&wx\_co\=1/g, '') //获取图片的url
		var index = img_filename.lastIndexOf("\/")  

		type = img_filename.substring(index + 1, img_filename.length).split(".")[1]

		var img_shortname = Math.random().toString(36).substr(2)

		var img_url = folder + '/' + img_shortname+'.'+type

		var url = img_src.replace('http:', 'https:')

		var conf = JSON.parse(fs.readFileSync('./config.json'))
		var policy
		if (conf.PolicyFile) {
			policy = fs.readFileSync(conf.PolicyFile).toString('utf-8')
		}

		var sts = new STS({
			accessKeyId: conf.AccessKeyId,
			accessKeySecret: conf.AccessKeySecret,
		})

		http.get(url,function(res){
			var chunks = [] //用于保存网络请求不断加载传输的缓冲数据
			var size = 0　　 //保存缓冲数据的总长度

			res.on('data',function(chunk){
				chunks.push(chunk)　
				size += chunk.length　　//累加缓冲数据的长度
			})

			res.on('end',function(err){
				var data = Buffer.concat(chunks, size)
				// console.log(Buffer.isBuffer(data))
				var base64Img = data.toString('base64')　　//将Buffer对象转换为字符串并以base64编码格式显示
				// console.log(base64Img)　

				co(function* () {
					var token = yield sts.assumeRole(conf.RoleArn, policy, conf.TokenExpireTime)
					var client = new OSS({
						region: conf.region,
						accessKeyId: token.credentials.AccessKeyId,
						accessKeySecret: token.credentials.AccessKeySecret,
						stsToken: token.credentials.SecurityToken,
						bucket: conf.bucket
					})
					var result = yield client.put(img_url, new Buffer(base64Img, 'base64'))
					// console.log(result)
				}).catch(function (err) {
					// console.log(err)
				})

			})
		})

		return {"url":'https://oss.' + conf.bucket+'.com/' + img_url, "Ourl":item.url}
	})
	res.json(data)
})

app.post('/getwxarticle', function (req, res) {
	var url = req.body.url.replace('http:', 'https:')
	http.get(url, function (resq) {
		var html = ''
		resq.setEncoding('utf-8')
		//监听data事件，每次取一块数据
		resq.on('data', function (chunk) {   
				html += chunk
		})
		//监听end事件，如果整个网页内容的html都获取完毕，就执行回调函数
		resq.on('end', function () {
			var $ = cheerio.load(html) //采用cheerio模块解析html
			data = $('div#js_content').html().replace(/(\<qqmusic).*(\/qqmusic>)/ig,'</p>')
			var str = 'data-src="'
			var data = data.replace(new RegExp(str,"gm"),'src="')
			data = data.replace(/(\<mp-miniprogram).*(\/span><\/span><\/span><\/span><\/p>)/ig,'</p>')
			data = data.replace(/(\<iframe).*(\/iframe>)/ig,'')
			// data = unescape(data.replace(/(&#x)(\w{1,4});/gi,'%u$2'))
			data = unescape(data.replace(/\\u/g,"%u"));
			//再对实体符进行转义
			//有x则表示是16进制，$1就是匹配是否有x ，$2就是匹配出的第二个括号捕获到的内容，将$2以对应进制表示转换
			data = data.replace(/&#(x)?(1)?(\w+);/g,function($,$1,$2,$3){
				if(!$2){
					return String.fromCharCode(parseInt($3,$1?16:10))
				}else{
					return $
				}
		 });
			res.json({data:data})
		})
	})
})

app.listen(1513, function () {
	console.log('App started.')
})